package avicit.bdp.dgs.mdm.utils.api;

import avicit.bdp.dgs.mdm.utils.api.request.RequestAdapter;
import avicit.bdp.dgs.mdm.utils.api.request.RequestAdapterUtil;
import avicit.bdp.dgs.mdm.utils.enums.Method;
import avicit.platform6.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-12-11 11:35
 * @类说明：
 * @修改记录：
 */
public class HttpUtil {

    private static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * API请求方式
     */
    private String method;
    private int timeout;

    public HttpUtil(String method, Integer timeout){
        this.method = method;
        if(timeout == null){
            this.timeout = 120 * 1000;
        }else{
            this.timeout = timeout * 1000;
        }
        LOG.info("接口超时时间:{}", this.timeout);
    }

    /**
     * 远程调用API接口
     */
    public String remoteCallApi(String applicationCode, String authCode, String logId, String data, String url) {
        Method method = Method.getMethod(this.method);
        switch (method) {
            case GET:
            case POST:
                return callApi(applicationCode, authCode, logId, data, url);
            default:
                String msg = String.format("不支持的请求类型%s", this.method);
                LOG.error(msg);
                throw new BusinessException(msg);
        }
    }

    /**
     * API接口调用
     */
    private String callApi(String applicationCode, String authCode, String logId, String data, String url){
        RequestAdapter requestAdapter = RequestAdapterUtil.getRequestAdapter(this.method, this.timeout);
        return requestAdapter.callApi(applicationCode, authCode, logId, data, url);
    }

}
